import { Scene_GM_Page, Scene_Prefab, UI_Layer } from "../../constants/ui_def";
import { gg } from "../../frame/gg";
import { he } from "../../frame/he";
import { common } from "../../login/common";


const { ccclass, property } = cc._decorator;

@ccclass
export class UiManager extends cc.Component {

    canvasSize: cc.Size // 基础Canvas大小
    rootNode: cc.Node                // 根节点
    loadCount: 0                 // 加载计数
    lastScene: ""      // 最后场景
    preScene: ""      // 访问前场景
    loadOpenCount: 0            // 打开加载节点计数
    loadCloseCount: 0    // 关闭加载节点计数

    pool_list: []       // 已经加载的池子
    // 提示
    tips: 'tip'[]
    tipId: number = 0
    pageDict: {}
    initInfo() {
        this.pageDict = {}  // 页面字典
        this.addRoot(cc.find("Canvas"))
        cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.updateInfo, this)//监听运行新场景后的事件
        cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LOADING, this.clearInfo, this)//监听场景加载前的事件
    }
    // 隐藏化当前加载场景内容
    // 等所有内容加载完成后出现
    updateInfo(currentScene) {
        // 清除资源 关闭声音
        cc.sys.garbageCollect()
        // 场景增加UI子层级
        if (this.lastScene) {
            this.preScene = this.lastScene
        }
        this.lastScene = currentScene.name//当前场景名字
        let canvasNode = currentScene.getChildByName("Canvas")//找到场景中的画布Canvas
        canvasNode.opacity = 0  //设置透明度为0
        this.canvasSize = canvasNode.getContentSize()//记录比例
        // 计数清空
        this.loadOpenCount = 0
        this.loadCloseCount = 0

        let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
        let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height

        // 比例调整
        let f = screen_size >= design_size
        cc.Canvas.instance.fitHeight = f
        cc.Canvas.instance.fitWidth = !f

        this.addRoot(canvasNode)
        this.pageDict = {}
        // // 增加过度动画//暂时取消
        if (common.transition_list.indexOf(this.lastScene) >= 0) {
            gg.uiManager.addPage(UI_Layer.Load, {
                name: "transition",
                url: "base/transition"
            })
        }
        // 场景预制体加载
        if (Scene_Prefab[this.lastScene] && Scene_Prefab[this.lastScene].length) {
            for (let i = 0; i < Scene_Prefab[this.lastScene].length; i++) {
                let info = {
                    name: '',
                    type: null,
                    bundle: ''
                }
                if (typeof Scene_Prefab[this.lastScene][i] === 'string') {
                    info.name = Scene_Prefab[this.lastScene][i]
                    info.type = cc.Prefab
                } else {
                    info = Scene_Prefab[this.lastScene][i]
                }
                let loadres = he.Load.get(info.name, info.type, null)
                if (loadres) {
                    this.loadCount += 1
                    if (Scene_Prefab[this.lastScene].length == this.loadCount) {
                        canvasNode.opacity = 255
                        let canvasScript = canvasNode.getComponent(currentScene.name.toLowerCase())
                        if (canvasScript.initInfo) {
                            canvasScript.initInfo()
                            this.open_GM()
                        }
                    }
                } else {
                    he.Load.loadRes(info.name, info.type, this.addLoadCount.bind(this), info.bundle)
                }
            }
        } else {
            let canvasScript = canvasNode.getComponent(currentScene.name.toLowerCase())
            if (canvasScript && canvasScript.initInfo) {
                canvasNode.opacity = 255
                canvasScript.initInfo()
                this.open_GM()
            } else {
                console.error("要么是场景没脚本,要么是场景没保存")
            }
        }
    }
    addRoot(canvasNode) {
        let uiRoot = canvasNode.getChildByName("uiRoot")//找到场景中的uiRoot
        if (!uiRoot) {  //如果uiRoot没有找到就new一个
            uiRoot = new cc.Node()
            uiRoot.name = 'uiRoot'
            uiRoot.position = cc.Vec2.ZERO
            this.canvasSize = canvasNode.getContentSize()
            uiRoot.setContentSize(this.canvasSize)

            let widgetCom = uiRoot.addComponent(cc.Widget)
            widgetCom.isAlignHorizontalCenter = true
            widgetCom.isAlignVerticalCenter = true
            widgetCom.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE
            canvasNode.insertChild(uiRoot, 0)
            widgetCom.updateAlignment()
        }
        this.rootNode = uiRoot
        for (let key in UI_Layer) {
            let layer = UI_Layer[key]
            let layerNode = new cc.Node()
            layerNode.setContentSize(this.canvasSize)
            layerNode.name = key
            uiRoot.insertChild(layerNode, layer)//在uiRoot中插入子节点key
        }
    }
    // 打开GM 面板
    open_GM() {
        if (common.gm_switch) {
            if (Scene_GM_Page[this.lastScene] && Scene_GM_Page[this.lastScene].length) {
                for (let i = 0; i < Scene_GM_Page[this.lastScene].length; i++) {
                    let gm_info = Scene_GM_Page[this.lastScene][i]
                    this.addPage(gm_info.layer, {
                        name: gm_info.name,
                        script: gm_info.script,
                        url: 'gm/' + gm_info.name,
                    })
                }
            }
        }
    }
    // 场景加载计数
    addLoadCount(err, asset) {
        if (asset) {
            this.loadCount += 1
            if (Scene_Prefab[this.lastScene].length == this.loadCount) {
                let currentScene = cc.director.getScene()
                let canvasNode = currentScene.getChildByName("Canvas")
                let canvasScript = canvasNode.getComponent(currentScene.name.toLowerCase())//获得和场景名字一样的组件
                canvasNode.opacity = 255
                if (canvasScript.initInfo) {
                    canvasScript.initInfo()
                    this.open_GM()
                }
            }
        }
    }
    // 增加页面
    addPage(layer, param) {
        param.layer = layer
        if (this.pageDict[param.name + '_' + layer]) {//如果字典中的值存在，就是这个按钮已经存在
            let uiBaseNode = this.getNode(layer, param.name)
            let uiBaseScript
            if (uiBaseNode != false) {
                uiBaseScript = uiBaseNode.getComponent('uiBase')//获得uiBase组件
            }
            uiBaseScript.initInfo(param)//初始化这个按钮
            return
        }
        let uiBaseNode = cc.instantiate(he.Load.get("base/uiBase", null, null))//如果这个按钮不存在，那就通过预制件孵化出来
        uiBaseNode.setContentSize(this.canvasSize)//设置节点初始大小
        this.addNode(layer, uiBaseNode)//增加一个预制体
        let uiBaseScript = uiBaseNode.getComponent('uiBase')//获得uiBase组件
        this.pageDict[param.name + '_' + layer] = true//将这个按钮记录到字典中，下次直接初始化，不再生成
        uiBaseScript.initInfo(param)//初始化这个按钮
        return uiBaseScript.page_node
    }
    // 获得页面节点
    getPage(layer, nodeName) {
        let parentNode = this.getNode(layer, nodeName)
        if (parentNode) {
            let uiBase = parentNode.getComponent('uiBase')
            if (uiBase) {
                return uiBase.page_node
            } else {
                return null
            }
        }
        return null
    }
    // 检查页面是否激活状态
    checkPage(layer, nodeName) {
        let parentNode = this.getNode(layer, nodeName)
        if (parentNode) {
            return parentNode.active
        }
        return false
    }
    // 删除页面
    delPage(layer, nodeName) {
        let parentNode = this.getNode(layer, nodeName)
        this.pageDict[nodeName + '_' + layer] = null
        if (parentNode) {
            parentNode.removeFromParent()
            parentNode.destroy()
        }
    }
    // 关闭页面
    closePage(layer, nodeName) {
        let parentNode = this.getNode(layer, nodeName)
        if (parentNode) {
            let uiBase = parentNode.getComponent("uiBase")
            uiBase.closePage()
        }
    }
    // 单纯的增加一个预制体
    addNode(layer, node) {
        let name = ''
        for (let key in UI_Layer) {
            if (layer == UI_Layer[key]) {
                name = key
            }
        }
        this.rootNode.getChildByName(name).addChild(node)
        return node
    }
    // 单纯的获得一个预制体
    getNode(layer, nodeName) {
        let name = ''
        for (let key in UI_Layer) {
            if (layer == UI_Layer[key]) {
                name = key
            }
        }
        if (this.rootNode.name) {
            return this.rootNode.getChildByName(name).getChildByName(nodeName)
        } else {
            return false
        }
    }
    // 单纯的删除一个预制体
    delNode(layer, nodeName) {
        let node = this.getNode(layer, nodeName)
        if (node) {
            node.removeFromParent()
            node.destroy()
        }
    }
    // 添加tip
    addTip(param) {
        // 直接使用微信弹窗
        if (typeof param == 'string') {
            param = {
                text: param
            }
        }
        let layer = UI_Layer.Msg
        if (param.type) {
            layer = param.type
        }
        if (!he.Pool.getPool('tip')) {
            he.Pool.createPoolSync('tip', 3, cc.Prefab, "base/tip")
        }
        let content = gg.uiManager.getNode(layer, 'tipContent')
        if (!content) {
            let contentPrefab = cc.instantiate(he.Load.get('uimod/tipContent', null, null))
            content = gg.uiManager.addNode(layer, contentPrefab)
        }
        this.tipId += 1
        if (this.tipId >= 10000) {
            this.tipId = 1
        }
        let tipnode = he.Pool.getElement('tip')
        let tip = tipnode.getComponent('tip')
        param.orderId = this.tipId
        // if (this.tips.length) {
        //     let initY = tipnode.height
        //     let margin = 5
        //     for (let i = this.tips.length - 1; i >= 0; i--) {
        //         if (i == this.tips.length - 1) {
        //             initY += 5
        //         } else {
        //             initY += tipnode.height + margin
        //         }
        //         if (this.tips[i].count <= this.tips[i].stayTime) {
        //             this.tips[i].count = 0
        //         }
        //         if (initY > this.tips[i].node.y)
        //             this.tips[i].node.y = initY
        //     }
        // }
        if (typeof content != "boolean") {
            content.addChild(tipnode)
        }
        tip.initInfo(param)
        this.tips.push(tip)
    }
    // delTip(id) {
    //     for (let i = 0; i < this.tips.length; i++) {
    //         if (id === this.tips[i].orderId) {
    //             this.tips.splice(i, 1)
    //             break
    //         }
    //     }
    // }
    // 通用加载
    // 一般用于遮罩 promise 加载
    switchLoad(status, force) {
        if (status) {
            this.loadOpenCount += 1
            this.addPage(UI_Layer.Load, {
                name: 'loading',
                url: 'base/loading',
                cover: true
            })
        } else {
            if (force) {
                this.loadCloseCount == this.loadOpenCount
                this.closePage(UI_Layer.Load, 'loading')
            } else {
                this.loadCloseCount += 1
                if (this.loadCloseCount >= this.loadOpenCount) {
                    this.closePage(UI_Layer.Load, 'loading')
                }
            }
        }
    }
    // 清楚当前场景已经被释放 但是uiBase关联脚本还存在的内容
    clearInfo(event) {
        this.loadCount = 0
        for (let key in this.pageDict) {
            if (this.pageDict[key] && this.pageDict[key].closeUI) {
                this.pageDict[key].closeUI()
            }
        }
    }
}
